package cn.evun.tms.generator.task;

import cn.evun.tms.generator.framework.AbstractApplicationTask;
import cn.evun.tms.generator.framework.context.ApplicationContext;
import cn.evun.tms.generator.handler.BaseHandler;
import cn.evun.tms.generator.handler.impl.ServiceHandler;
import cn.evun.tms.generator.model.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ServiceTask extends AbstractApplicationTask {

	private static String SERVICE_FTL = "template/Service.ftl";

	List<EntityInfo> entityInfos = null;
	List<ServiceInfo> serviceInfos = null;
	List<DtoInfo> dtoInfos = null;

	protected boolean doBefore(ApplicationContext context) throws Exception {

		List<DtoInfo> dtoInfos = (List<DtoInfo>) context.getAttribute("dtoList");
		List<ServiceInfo> serviceInfos = (List<ServiceInfo>) context.getAttribute("serviceInfos");
		List<EntityInfo> entityInfos = (List<EntityInfo>) context.getAttribute("entityInfos");
		HashMap<String, TableInfo> tableInfos = (HashMap<String, TableInfo>) context.getAttribute("tableInfos");
		this.entityInfos = entityInfos;
		this.dtoInfos = dtoInfos;
		this.serviceInfos = serviceInfos;

		for (int i = 0; i < serviceInfos.size(); i++) {
			DtoInfo dtoInfo = dtoInfos.get(i);
			ServiceInfo serviceInfo = serviceInfos.get(i);
			EntityInfo entityInfo = entityInfos.get(i);
			TableInfo tableInfo = tableInfos.get(entityInfo.getTableName());

			serviceInfo.setDtoInfo(dtoInfo);
			serviceInfo.setTableInfo(tableInfo);
		}

		return true;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected boolean doInternal(ApplicationContext context) throws Exception {
		logger.info("开始生成service。。。");

		List<ServiceInfo> serviceInfos = (List<ServiceInfo>) context.getAttribute("serviceInfos");

		BaseHandler<ServiceInfo> baseHandler = null;
		for (ServiceInfo serviceInfo : serviceInfos) {
			baseHandler = new ServiceHandler(SERVICE_FTL, serviceInfo);
			baseHandler.execute(context);
		}

		logger.info("结束生成service。。。");
		return false;
	}


	@Override
	protected void doAfter(ApplicationContext context) throws Exception {
		super.doAfter(context);

		List<ControllerInfo> controllerInfos = new ArrayList<ControllerInfo>();
		// 组装Dao信息、组装Vo信息
		for (int i = 0; i < entityInfos.size(); i++) {
			EntityInfo entityInfo = entityInfos.get(i);
			ControllerInfo controllerInfo = new ControllerInfo();
			controllerInfo.setClassName(entityInfo.getClassName() + "Controller");
			controllerInfo.setServiceInfo(serviceInfos.get(i));
			controllerInfo.setDtoInfo(dtoInfos.get(i));
			controllerInfo.setEntityInfo(entityInfo);
			controllerInfo.setLowerEntityName(entityInfo.getEntityName().substring(0, 1).toLowerCase() + entityInfo.getEntityName().substring(1));
			controllerInfos.add(controllerInfo);
		}
		context.setAttribute("controllerInfos", controllerInfos);
	}
}
